package com.yc.testupload.consumer;

import com.yc.testupload.model.Account;
import com.yc.testupload.publisher.PlatformPublisherFactory;
import com.yc.testupload.dao.AccountDAO;
import java.util.concurrent.ConcurrentHashMap;

import com.rabbitmq.client.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.yc.testupload.util.RabbitMQConfig;
import com.yc.testupload.publisher.PlatformPublisher;
import com.yc.testupload.model.PublishResult;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 批量发布任务消息消费者
 * 负责从消息队列获取批量发布任务并执行实际的发布操作
 */
public class BatchPublishConsumer {
    private static final Logger logger = LogManager.getLogger(BatchPublishConsumer.class);
    private final String queueName;
    private final PlatformPublisherFactory publisherFactory;
    private final AccountDAO accountDAO;

    public BatchPublishConsumer() {
        this.queueName = RabbitMQConfig.WECHAT_PUBLISH_QUEUE;
        this.publisherFactory = new PlatformPublisherFactory();
        this.accountDAO = new AccountDAO();
    }

    /**
     * 启动消费者，开始监听队列
     */
    public void start() {
        try {
            // 获取RabbitMQ连接
            Connection connection = RabbitMQConfig.getConnection();
            Channel channel = connection.createChannel();

            // 声明队列（持久化）
            boolean durable = true;
            channel.queueDeclare(queueName, durable, false, false, null);

            // 设置每次只处理一个消息
            channel.basicQos(1);

            logger.info("批量发布消费者开始监听队列: {}", queueName);

            // 创建消费者
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");

                try {
                    // 处理批量发布任务
                    processBatchPublishTask(message);

                    // 确认消息处理成功
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } catch (Exception e) {
                    logger.error("处理批量发布任务失败: {}", e.getMessage(), e);
                    // 更新任务状态为FAILED
                    try {
                        JSONObject taskJson = new JSONObject(message);
                        String taskId = taskJson.getString("taskId");
                        logger.error("任务处理失败，任务ID: {}, 错误信息: {}", taskId, e.getMessage());
                    } catch (Exception parseError) {
                        logger.error("解析任务ID失败: {}", parseError.getMessage());
                    }

                    // 记录错误，但仍然确认消息，避免消息重复处理
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                }
            };

            // 注册消费者，autoAck设置为false，手动确认
            channel.basicConsume(queueName, false, deliverCallback, consumerTag -> {
            });

        } catch (IOException | TimeoutException e) {
            logger.error("启动批量发布消费者失败: {}", e.getMessage(), e);
            throw new RuntimeException("启动批量发布消费者失败: " + e.getMessage(), e);
        }
    }

    /**
     * 处理批量发布任务
     */
    private void processBatchPublishTask(String message) throws Exception {
        JSONObject taskJson = new JSONObject(message);
        String taskId = taskJson.getString("taskId");
        String taskType = taskJson.optString("taskType");
        String platformType = taskJson.optString("platformType");

        logger.info("开始处理批量发布任务，任务ID: {}, 任务类型: {}, 平台类型: {}",
                taskId, taskType, platformType);

        // 记录任务开始处理
        logger.info("任务开始处理，平台类型: {}", platformType);

        try {
            if ("MULTIPLE_ACCOUNTS_PUBLISH".equals(taskType)) {
                // 获取账号列表
                JSONArray accountsArray = taskJson.getJSONArray("accounts");
                Map<String, Object> content = convertJsonToMap(taskJson.getJSONObject("content"));

                // 统计信息
                int totalAccounts = accountsArray.length();
                int successCount = 0;
                int failedCount = 0;

                logger.info("开始处理{}个账号的发布任务，内容标题: {}",
                        totalAccounts, content.getOrDefault("title", "无标题"));

                // 逐个账号进行发布
                for (int i = 0; i < accountsArray.length(); i++) {
                    JSONObject accountJson = accountsArray.getJSONObject(i);
                    String accountName = accountJson.getString("accountName");

                    try {
                        // 创建账号对象
                        Account account = new Account();
                        account.setId(accountJson.getInt("accountId"));
                        account.setAccountType(accountJson.getString("accountType"));
                        account.setAccountId(accountJson.getString("appId"));
                        account.setAccountName(accountName);
                        account.setAppSecret(accountJson.optString("appSecret", ""));

                        // 获取对应的发布器
                        PlatformPublisher publisher = publisherFactory.getPublisher(platformType);
                        if (publisher != null) {
                            // 执行发布操作
                            PublishResult result = publisher.publish(account, content);

                            if (result.isSuccess()) {
                                successCount++;
                                logger.info("账号 {} 发布成功", accountName);
                            } else {
                                failedCount++;
                                logger.error("账号 {} 发布失败: {}", accountName, result.getMessage());
                            }
                        } else {
                            failedCount++;
                            logger.error("未找到平台类型 {} 的发布器，账号 {} 发布失败",
                                    platformType, accountName);
                        }
                    } catch (Exception e) {
                        failedCount++;
                        logger.error("处理账号 {} 时出错: {}", accountName, e.getMessage(), e);
                    }
                }

                // 记录任务处理完成时间
                logger.info("任务处理完成时间: {}", System.currentTimeMillis());

                // 记录任务完成情况
                logger.info("批量发布任务 {} 处理完成，成功: {}, 失败: {}, 总计: {}",
                        taskId, successCount, failedCount, totalAccounts);
            } else {
                logger.warn("不支持的任务类型: {}", taskType);
            }
        } catch (Exception e) {
            logger.error("处理批量发布任务时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 将JSONObject转换为Map
     */
    private Map<String, Object> convertJsonToMap(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                map.put(key, convertJsonToMap((JSONObject) value));
            } else if (value instanceof JSONArray) {
                map.put(key, ((JSONArray) value).toList());
            } else {
                map.put(key, value);
            }
        }
        return map;
    }
}